<template>
  <page-meta :root-font-size="$rootFontSize"></page-meta>
  <view>
    <!--短信登录-->
    <view class="mx-9 pt-32">
      <u--form :model="form" :rules="rules" ref="form" errorType="toast">
        <u-form-item class="px-5 rounded-full bg-inputGray" prop="phone">
          <u--input
            v-model="form.phone"
            type="number"
            shape="circle"
            border="none"
            fontSize="32rpx"
            color="#333333"
            placeholderStyle="color: #999999"
            placeholder="手机号"
            clearable
          >
          </u--input>
        </u-form-item>
        <u-form-item class="px-5 rounded-full bg-inputGray mt-4" prop="vcode">
          <!-- 注意：由于兼容性差异，如果需要使用前后插槽，nvue下需使用u--input，非nvue下需使用u-input -->
          <u-input
            v-model="form.vcode"
            type="number"
            shape="circle"
            border="none"
            fontSize="32rpx"
            color="#333333"
            placeholderStyle="color: #999999"
            placeholder="短信验证码"
            clearable
          >
            <template slot="suffix">
              <u-code
                ref="uCode"
                @change="codeChange"
                @end="codeEnd"
                :seconds="seconds"
                changeText="X秒重新获取"
                class="text-light text-sm"
              ></u-code>
              <view @tap="getCode" :text="tips" class="text-sm text-primary">{{
                tips
              }}</view>
            </template>
          </u-input>
        </u-form-item>
      </u--form>
      <view
        class="common-btn bg-primary text-center rounded-full text-white mt-9"
        @click="smsLogin"
        >确认</view
      >
    </view>
    <web-view :src="myUrl" @message="handleMessage" v-if="isWeb"></web-view>
  </view>
</template>

<script>
import { login } from '../../services/user-details';
import { sendCode, sendVcodeLog } from '../../../services/user';

export default {
  data() {
    return {
      //webview页面携带参数天御行为验证码AppId
      myUrl:
        '/static/html/index.html?id=' +
        uni.getStorageSync('autoBuy' + uni.getStorageSync('autoBuy-platformId'))
          .captchaAppId
          ? uni.getStorageSync(
              'autoBuy' + uni.getStorageSync('autoBuy-platformId')
            ).captchaAppId
          : process.env.VUE_APP_SDK_APP_ID,
      //是否显示webview
      isWeb: false,
      isShow: true,
      tips: '',
      canGetCode: false,
      seconds: 60,
      form: {
        phone: '',
        vcode: '',
      },
      rules: {
        phone: [
          {
            type: 'string',
            required: true,
            message: '请输入手机号',
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value);
            },
            message: '手机号码不正确',
          },
        ],
        code: {
          required: true,
          message: '请输入短信验证码',
        },
      },
    };
  },
  async created() {},
  methods: {
    //发送行为验证码日志(密-明)
    async _sendVcodeLog() {
      let params = {
        phone: this.form.phone,
        vcodeType: 'pcode',
      };
      const { code, data } = await sendVcodeLog(params);
      if (code != 200) return;
      //console.log(data);
    },
    //路由跳转
    goTo(url) {
      this.$Router.push({
        name: url,
      });
    },
    //获取文字
    codeChange(text) {
      this.tips = text;
    },
    codeEnd() {
      this.canGetCode = false;
    },
    //获取验证码 => 天御行为验证码
    async getCode() {
      if (this.form.phone == '') {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none',
        });
        return;
      }
      if (!this.$u.test.mobile(this.form.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
        });
        return;
      }
      //#ifdef H5
      this.$Captcha.show();
      uni.$on('gitTicket', (res) => {
        this.getCodeTo(res);
        uni.$off('gitTicket');
      });
      //#endif
      //#ifdef APP-PLUS
      this.isWeb = true;
      //#endif
    },
    //获取验证码
    async getCodeTo(res) {
      //短信接口方法
      //console.log(res);
      if (res.ret != 0) return;
      let params = {
        captchaVO: {
          randstr: res.randstr,
          ticket: res.ticket,
        },
        phone: this.form.phone,
        smsType: 'login',
      };
      //console.log(params);
      const { code, data } = await sendCode(params);
      if (code != 200) return;
      this.seconds = data;
      this._sendVcodeLog();
      if (this.$refs.uCode.canGetCode) {
        uni.showLoading({
          title: '正在获取验证码',
        });
        setTimeout(() => {
          uni.hideLoading();
          uni.$u.toast('验证码已发送');
          this.canGetCode = this.$refs.uCode.canGetCode;
          this.$refs.uCode.start();
        }, 1000);
      } else {
        uni.$u.toast('倒计时结束后再发送');
      }
    },
    //短信登录
    async smsLogin() {
      try {
        await this.$refs.form.validate();
        let params = {
          vcode: this.form.vcode,
          phone: this.form.phone,
          loginType: 'vcode',
        };
        //console.log(params);
        const { code, data } = await login(params);
        if (code != 200) return;
        const { accessToken, expireTime } = data;
        // console.log(accessToken);
        uni.setStorageSync(
          'tokenBuy' + process.env.VUE_APP_PLATFORMID,
          accessToken
        );
        uni.setStorageSync('expireAtBuy', expireTime * 1000);
        await this.$store.dispatch('getUser');
        // 登录成功跳转首页
        uni.$u.toast('登录成功~');
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index',
          });
        }, 1000);
      } catch (error) {
        console.error(error);
      }
    },
    //html/index页面发来的消息
    handleMessage(e) {
      uni.setNavigationBarTitle({
        title: '短信登录',
      });
      let data = e.detail.data[0];
      if (data.ret === 2) {
        //console.log('用户关闭验证码');
        this.isWeb = false;
      }
      if (data.ret === 0) {
        //console.log('用户验证码通过');
        //console.log(data);
        this.getCodeTo(data);
        this.isWeb = false;
      }
    },
  },
};
</script>

<style></style>
